package com.skywolf.chem.tencent.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ServiceException;
import com.skywolf.chem.live.entity.Live;
import com.skywolf.chem.live.service.ILiveService;
import com.skywolf.chem.tencent.utils.TLSSigAPIv2;
import com.skywolf.chem.utils.HttpUtils;
import com.skywolf.chem.utils.SysConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by pei_pei on 2020/12/11.
 */
@Service
public class ImService {
    Logger logger = LoggerFactory.getLogger(ImService.class);

    @Autowired
    ILiveService liveService;

    /**
     * 获取IM签名
     * @param userid
     * @param expire
     * @return
     */
    public String getUseSig(String userid, Long expire) {
        try{
            if(expire==null || expire==0){
                expire = 86400L;
            }
            String accessKeyId = SysConfig._this.getProperty("tencent.appid");
            String key = SysConfig._this.getProperty("tencent.key");
            TLSSigAPIv2 v2 = new TLSSigAPIv2(Long.valueOf(accessKeyId),key);
            return v2.genUserSig(userid,expire);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取创建群里的im签名
     * @return
     */
    public String getGroupSig(String adminUser) {
        try{
            Long expire = 86400L;
            if(StringUtils.isBlank(adminUser)){
                adminUser = "administrator";
            }
            String accessKeyId = SysConfig._this.getProperty("tencent.appid");
            String key = SysConfig._this.getProperty("tencent.key");
            TLSSigAPIv2 v2 = new TLSSigAPIv2(Long.valueOf(accessKeyId),key);
            return v2.genUserSig(adminUser,expire);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public String getGroupId(String liveId) throws ServiceException{
        Boolean bl = true;
        Integer count = 0;
        String appid = SysConfig._this.getProperty("tencent.appid");
        String adminUser = "administrator";
        String sig = getGroupSig(adminUser);
        Integer randomStr = new Random().nextInt(java.lang.Integer.MAX_VALUE);
        String url = "https://console.tim.qq.com/v4/group_open_http_svc/create_group?sdkappid="+appid+"&identifier="+adminUser+"&usersig="+sig+"&random="+randomStr+"&contenttype=json";
        JSONObject sendData = new JSONObject();
        sendData.put("Type","AVChatRoom");
        sendData.put("Name",liveId);
        while (bl){
            count++;
            try{
                if(count>2){
                    bl = false;
                }
                String response = HttpUtils.post(url,sendData,null);
                if(StringUtils.isNotBlank(response)){
                    JSONObject obj = JSONObject.parseObject(response);
                    if(obj.getString("ActionStatus").equalsIgnoreCase("FAIL") && obj.getString("ErrorCode").equalsIgnoreCase("10036")){
                        getAllGroupId(sig);
                    }
                    if(obj.getString("ActionStatus").equalsIgnoreCase("ok")){
                        bl = false;
                        return obj.getString("GroupId");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        throw new ServiceException("获取群id失败");
    };


    public void getAllGroupId(String sig) throws ServiceException{
        try{
            String appid = SysConfig._this.getProperty("tencent.appid");
            String adminUser = "administrator";
            if(StringUtils.isBlank(sig)){
                sig = getGroupSig(adminUser);
            }
            Integer randomStr = new Random().nextInt(java.lang.Integer.MAX_VALUE);
            String url = "https://console.tim.qq.com/v4/group_open_http_svc/get_appid_group_list?sdkappid="+appid+"&identifier="+adminUser+"&usersig="+sig+"&random="+randomStr+"&contenttype=json";
            JSONObject sendData = new JSONObject();
            sendData.put("Limit",1000);
            sendData.put("Next",0);
            String response = HttpUtils.post(url,sendData,null);
            if(StringUtils.isNotBlank(response)){
                JSONObject obj = JSONObject.parseObject(response);
                if(obj.getString("ActionStatus").equalsIgnoreCase("ok")){
                    List<String> groupIds = new ArrayList<>();
                    JSONArray arr = obj.getJSONArray("GroupIdList");
                    for (int i=0;i<arr.size();i++) {
                        groupIds.add(arr.getJSONObject(i).getString("GroupId"));
                    }
                    if(groupIds.size()>0){
                        List<Live> live =liveService.getGroupInfo(groupIds);
                        for (Live item:live) {
                            try{
                                //删除群组
                                delGroupId(sig,item.getGroupId());
                                item.setGroupId(" ");
                                liveService.updateById(item);
                            }catch (Exception e){
                                logger.error("getAllGroupId live:"+ JSON.toJSONString(item)+",error:{}",e);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    };

    /**
     * 解散群组
     * @param sig
     * @throws ServiceException
     */
    public void delGroupId(String sig,String groupId) throws ServiceException{
        try{
            String appid = SysConfig._this.getProperty("tencent.appid");
            String adminUser = "administrator";
            if(StringUtils.isBlank(sig)){
                sig = getGroupSig(adminUser);
            }
            Integer randomStr = new Random().nextInt(java.lang.Integer.MAX_VALUE);
            String url = "https://console.tim.qq.com/v4/group_open_http_svc/destroy_group?sdkappid="+appid+"&identifier="+adminUser+"&usersig="+sig+"&random="+randomStr+"&contenttype=json";
            JSONObject sendData = new JSONObject();
            sendData.put("GroupId",groupId);
            String response = HttpUtils.post(url,sendData,null);
            if(StringUtils.isNotBlank(response)){
                JSONObject obj = JSONObject.parseObject(response);
                if(obj.getString("ActionStatus").equalsIgnoreCase("ok")){
                    return;
                }
            }
        }catch (Exception e){
            logger.error("delGroupId groupId:"+ groupId+",error:{}",e);
        }
    };



}
